﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Diagnostics;
using System.Reflection;
namespace Gobang
{
    public partial class Lobby : Form
    {
        private Client clientProxy;
        public Lobby()
        {
            InitializeComponent();
            clientProxy = new Client();
            clientProxy.m_requestHandler = HandleMsg;
        }
        private void HandleMsg(object[] args)
        {
            List<object> Args = new List<object>(args);
            if (args[0].GetType() != typeof(string))
            {
                Debug.WriteLine("first argument should be string");
                return;
            }
            string funcname = args[0] as string;
            Args.RemoveAt(0);
            MethodInfo minfo = this.GetType().GetMethod(funcname);
            if (minfo != null)
            {
                try
                {
                    minfo.Invoke(this, Args.ToArray());
                    Debug.WriteLine("ClientTool::" + funcname + " executed.");
                }
                catch (TargetParameterCountException e)
                {
                    Debug.WriteLine("ClientTool::" + funcname + " execute error: " + e.Message);
                }
                catch (TargetInvocationException e)
                {
                    Debug.WriteLine("ClientTool::" + funcname + " execute error: " + e.Message);
                }
            }
            else
            {
                Debug.WriteLine("ClientTool::" + funcname + " not found.");
            }
        }
        private void Lobby_Load(object sender, EventArgs e)
        {
            bool res = clientProxy.Connect("47.103.69.4", 1009);
            if (!res)
            {
                Debug.WriteLine("Connect Server failed");
                MessageBox.Show("连接服务器失败");
            }
            cmbGameType.SelectedIndex = 0;
        }

        private void btnSignIn_Click(object sender, EventArgs e)
        {
            if (textUserName.Text == null || textUserName.Text == "")
            {
                MessageBox.Show("昵称不能为空");
                return;
            }
            clientProxy.SendParams("SIGN_IN", textUserName.Text);
            if (clientProxy != null && clientProxy.m_client.IsConnected())
            {
                clientProxy.SendParams("REQUEST_ROOM_INFO");
            }
        }
        public void SIGN_IN_SUCCESS()
        {
            labelInfo.Text = "登录成功";
        }
        public void SIGN_IN_FIRST()
        {
            labelInfo.Text = "请先登录";
        }
        public void ALREADY_SIGN_UP()
        {
            labelInfo.Text = "该账户已经注册";
        }
        public void SIGN_UP_FAILED()
        {
            labelInfo.Text = "注册失败";
        }
        public void SIGN_UP_SUCCESS()
        {
            labelInfo.Text = "注册成功";
        }
        public void SIGN_UP_FIRST()
        {
            labelInfo.Text = "请先注册账户";
        }
        public void ALREADY_INROOM()
        {
            labelInfo.Text = "已经在房间中";
        }
        public void OTHER_JOIN_ROOM(string name)
        {
            labelInfo.Text = name + "加入房间";
        }
        public void OTHER_LEAVE_ROOM(string name)
        {
            labelInfo.Text = name + "退出房间";
        }
        public void ALREADY_SIGN_IN()
        {
            labelInfo.Text = "已经登录成功，无需重复登录";
        }
        private void Lobby_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (clientProxy.m_client.IsConnected())
            {
                clientProxy.SendParams("QUIT_LOBBY");    //退出大厅
                clientProxy.Close();
            }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            clientProxy.m_client.Tick();
        }
        public void CREATE_ROOM_SUCCESS()
        {
            labelInfo.Text = "创建房间成功";
            this.Text = string.Format("五子棋（房间号：{0}）", textRoom.Text);
            clientProxy.SendParams("REQUEST_ROOM_INFO");
        }
        public void CREATE_ROOM_FAILED()
        {
            labelInfo.Text = "创建房间失败，该房间号已存在";
        }
        public void ENTER_ROOM_FIRST()
        {
            labelInfo.Text = "请先加入房间";
        }
        public void ROOM_FULL()
        {
            labelInfo.Text = "房间已满";
        }
        public void JOIN_SUCCESS()
        {
            labelInfo.Text = "加入成功";
            this.Text = string.Format("五子棋（房间号：{0}）", textRoom.Text);
        }
        public void NOTIFY_READY(int state)
        {
            if (state == 1)
            {
                btnPrepare.Enabled = false;
            }
            else
            {
                btnPrepare.Enabled = true;
            }
        }
        public void OTHER_READY_STATE(int state, string name)
        {
            if (state == 1)
            {
                labelInfo.Text = name + "已准备";
            }
            else
            {
                labelInfo.Text = name + "未准备";
            }
        }
        public void ROOM_LAUNCH()
        {
            Form1 form = new Form1(clientProxy);
            this.Hide();
            form.roomID = textRoom.Text;
            form.ShowDialog();
            //退回大厅
            clientProxy.m_requestHandler = this.HandleMsg;
            this.Show();
        }
        private void btnJoin_Click(object sender, EventArgs e)
        {
            if (textRoom.Text != null && textRoom.Text != "")
            {
                clientProxy.SendParams("ROOM", textRoom.Text, textRoomName.Text);
            }
        }

        private void btnPrepare_Click(object sender, EventArgs e)
        {
            if (btnPrepare.Enabled)
            {
                clientProxy.SendParams("READY", 1);
            }
            else
            {
                clientProxy.SendParams("READY", 0);
            }
        }

        private void btnSignUp_Click(object sender, EventArgs e)
        {
            if (textUserName.Text == null || textUserName.Text == "")
            {
                labelInfo.Text = "昵称不能为空";
                return;
            }
            if (textUserName.Text.Contains(' '))
            {
                labelInfo.Text = "昵称不能包含空格";
                return;
            }
            clientProxy.SendParams("SIGN_UP", textUserName.Text);
        }
        private int GetSelectedGameType()
        {
            return cmbGameType.SelectedIndex + 1;
        }
        private void btnCreateRoom_Click(object sender, EventArgs e)
        {
            if (clientProxy!=null && clientProxy.m_client.IsConnected())
            {
                int gameType = GetSelectedGameType();
                clientProxy.SendParams("CREATE_ROOM", textRoom.Text, textRoomName.Text, gameType);
            }
        }
        public void UPDATE_ROOMINFO(string info)
        {
            List<string> roomInfos = new List<string>();
            while (info.Length!=0)
            {
                int s = info.IndexOf('{');
                int e = info.IndexOf('}');
                roomInfos.Add(info.Substring(s + 1, e - s - 1));
                info = info.Remove(s, e - s + 1);
            }
            listViewLobby.Items.Clear();
            foreach (string rInfo in roomInfos)
            {
                ListViewItem item = new ListViewItem(rInfo.Split('\n'), -1);
                listViewLobby.Items.Add(item);
                item.SubItems[2].Text = GetChineseGameName(item.SubItems[2].Text);
            }
        }
        public string GetChineseGameName(string engGameName)
        {
            if (engGameName == "Gobang")
                return "五子棋";
            return "游戏";
        }
        public void ROOM_NONE()
        {
            labelInfo.Text = "房间不存在";
        }
        private void btnRefreshLobby_Click(object sender, EventArgs e)
        {
            if (clientProxy != null && clientProxy.m_client.IsConnected())
            {
                clientProxy.SendParams("REQUEST_ROOM_INFO");
            }
        }

        private void listViewLobby_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (listViewLobby.SelectedItems.Count > 0)
            {
                ListViewItem item = listViewLobby.SelectedItems[0];
                textRoom.Text = item.Text;
                textRoomName.Text = item.SubItems[1].Text;
            }
        }
    }
}
